package v1

import (
	"strconv"

	"gitee.com/cyanbleeze/go-image-management/internal/service"
	"gitee.com/cyanbleeze/go-image-management/pkg/app"
	"gitee.com/cyanbleeze/go-image-management/pkg/errcode"
	"github.com/gin-gonic/gin"
)

type Category struct {
}

func NewCategory() Category {
	return Category{}
}

func (c Category) Create(ctx *gin.Context) {
	params := service.CreateCategoryRequest{}
	res := app.NewResponse(ctx)
	valid, errs := app.BindAndValid(ctx, &params)
	if !valid {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	svc := service.New(ctx)
	err := svc.CreateCategory(&params)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorCreateCategoryFail.WithDetails(err.Error()))
		return
	}
	res.ToResponse(gin.H{})
}

func (c Category) Update(ctx *gin.Context) {
	res := app.NewResponse(ctx)
	id, IDErr := strconv.Atoi(ctx.Param("id"))
	if IDErr != nil {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(IDErr.Error()))
		return
	}
	params := service.UpdateCategoryRequest{ID: uint(id)}
	valid, errs := app.BindAndValid(ctx, &params)
	if !valid {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	svc := service.New(ctx)
	err := svc.UpdateCategory(&params)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorUpdateCategoryFail.WithDetails(err.Error()))
		return
	}
	res.ToResponse(gin.H{})
}

func (c Category) Delete(ctx *gin.Context) {
	params := service.DeleteCategoryRequest{}
	res := app.NewResponse(ctx)

	id, err := strconv.Atoi(ctx.Param("id"))
	if err != nil {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(err.Error()))
		return
	}
	params.ID = uint(id)
	svc := service.New(ctx)
	err = svc.DeleteCategory(&params)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorDeleteCategoryFail.WithDetails(err.Error()))
		return
	}
	res.ToResponse(gin.H{})
}

func (c Category) List(ctx *gin.Context) {
	res := app.NewResponse(ctx)
	pager := app.Pager{
		Page:     app.GetPage(ctx),
		PageSize: app.GetPageSize(ctx),
	}
	svc := service.New(ctx)
	categoryList, err := svc.GetCategoryList(&pager)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorGetCategoryListFail.WithDetails(err.Error()))
		return
	}
	res.ToResponseList(categoryList, len(categoryList))
}
